/**
 * Copyright (C) 2018-2020
 * All rights reserved, Designed By www.yixiang.co

 */
package co.yixiang.mall.biz.quartz.utils;

import co.yixiang.common.core.exception.BadRequestException;
import co.yixiang.common.core.utils.StringUtil;
import co.yixiang.mall.common.quartz.domain.QuartzJobRebate;
import co.yixiang.upms.common.quartz.domain.QuartzJob;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

import static org.quartz.TriggerBuilder.newTrigger;

/**
 * @author hupeng
 * @date 2019-01-07
 */
@Slf4j
@Component
public class QuartzRebateManage {

    private static final String JOB_NAME = "TASK_REBATE";

    @Resource(name = "scheduler")
    private Scheduler scheduler;


    public void addJob(QuartzJobRebate quartzJob){
        try {
            // 构建job信息
            JobDetail jobDetail = JobBuilder.newJob(ExecutionRebateJob.class).
                    withIdentity(JOB_NAME + quartzJob.getId()).build();

            Trigger trigger;
            //cron为空则创建simpleSchedule
            if(StringUtil.isBlank(quartzJob.getCronExpression())){
                //创建simpleSchedule实现单次执行
                trigger = newTrigger()
                        .withIdentity(JOB_NAME + quartzJob.getId())
                        .withSchedule(SimpleScheduleBuilder.simpleSchedule())
                        .startAt(quartzJob.getExecuteTime())
                        .build();

            }else {
                //通过触发器名和cron 表达式创建 Trigger
                trigger = newTrigger()
                        .withIdentity(JOB_NAME + quartzJob.getId())
                        .startNow()
                        .withSchedule(CronScheduleBuilder.cronSchedule(quartzJob.getCronExpression()))
                        .build();
                //重置启动时间
                ((CronTriggerImpl)trigger).setStartTime(new Date());
            }
            trigger.getJobDataMap().put(QuartzJobRebate.JOB_KEY, quartzJob);

            //执行定时任务
            scheduler.scheduleJob(jobDetail,trigger);

            // 暂停任务
            if (quartzJob.getIsPause()) {
                pauseJob(quartzJob);
            }
        } catch (Exception e){
            log.error("创建定时任务失败", e);
            throw new BadRequestException("创建定时任务失败");
        }
    }


    /**
     * 更新job
     * @param quartzJob /
     */
    public void updateJob(QuartzJobRebate quartzJob){
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getId());
            Trigger trigger;
            if(StringUtil.isBlank(quartzJob.getCronExpression())) {
                trigger =
                        TriggerBuilder
                                .newTrigger()
                                .withIdentity(JOB_NAME + quartzJob.getId())
                                .withSchedule(
                                        SimpleScheduleBuilder
                                                .simpleSchedule()
                                                .withRepeatCount(0)
                                ).startAt(quartzJob.getExecuteTime())
                                .build();
            }else {
                trigger = scheduler.getTrigger(triggerKey);
                // 如果不存在则创建一个定时任务
                if(trigger == null){
                    addJob(quartzJob);
                    trigger =  scheduler.getTrigger(triggerKey);
                }
                ScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(quartzJob.getCronExpression());
                trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
                //重置启动时间
                ((CronTriggerImpl)trigger).setStartTime(new Date());
            }

            trigger.getJobDataMap().put(QuartzJob.JOB_KEY,quartzJob);

            scheduler.rescheduleJob(triggerKey, trigger);
            // 暂停任务
            if (quartzJob.getIsPause()) {
                pauseJob(quartzJob);
            }
        } catch (Exception e){
            log.error("更新定时任务失败", e);
            throw new BadRequestException("更新定时任务失败");
        }

    }

    /**
     * 删除一个job
     * @param quartzJob /
     */
    public void deleteJob(QuartzJobRebate quartzJob){
        try {
            JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId());
            scheduler.pauseJob(jobKey);
            scheduler.deleteJob(jobKey);
        } catch (Exception e){
            log.error("删除定时任务失败", e);
            throw new BadRequestException("删除定时任务失败");
        }
    }

    /**
     * 恢复一个job
     * @param quartzJob /
     */
    public void resumeJob(QuartzJobRebate quartzJob){
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getId());
            Trigger trigger;
            JobKey jobKey = null;

            //cron表达式
            if (!StringUtil.isBlank(quartzJob.getCronExpression())) {
                trigger = scheduler.getTrigger(triggerKey);
                // 如果不存在则创建一个定时任务
                if (trigger == null) {
                    addJob(quartzJob);
                }
            }
            jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId());
            scheduler.resumeJob(jobKey);
        } catch (Exception e){
            log.error("恢复定时任务失败", e);
            throw new BadRequestException("恢复定时任务失败");
        }
    }

    /**
     * 立即执行job
     * @param quartzJob /
     */
    public void runJobNow(QuartzJobRebate quartzJob){
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getId());
            Trigger trigger;
            JobKey jobKey = null;

            //cron表达式
            if (!StringUtil.isBlank(quartzJob.getCronExpression())) {
                trigger = scheduler.getTrigger(triggerKey);
                // 如果不存在则创建一个定时任务
                if (trigger == null) {
                    addJob(quartzJob);
                }
            }
            JobDataMap dataMap = new JobDataMap();
            dataMap.put(QuartzJob.JOB_KEY, quartzJob);
            jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId());
            scheduler.triggerJob(jobKey,dataMap);
        } catch (Exception e){
            log.error("定时任务执行失败", e);
            throw new BadRequestException("定时任务执行失败");
        }
    }

    /**
     * 暂停一个job
     * @param quartzJob /
     */
    public void pauseJob(QuartzJobRebate quartzJob){
        try {
            JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId());
            scheduler.pauseJob(jobKey);
        } catch (Exception e){
            log.error("定时任务暂停失败", e);
            throw new BadRequestException("定时任务暂停失败");
        }
    }
}
